//
// Created by liushuai on 18-8-23.
//

#include "Node.hpp"
#include <iostream>
Node::Node() {
    index = data = 0;
    pLChild = nullptr;
    pRChild = nullptr;
    pParent = nullptr;
}
Node* Node::searchNode(int nodeIndex) {
    if(this->index == nodeIndex)
        return this;
    //左孩子节点存不存在
    Node *temp = nullptr;
    if(this->pLChild!=nullptr)
    {
        //存在就看index和搜索的nodeIndex是不是相同
        if(this->pLChild->index == nodeIndex)
            return this->pLChild;
        else
        {
            temp = this->pLChild->searchNode(nodeIndex);
            if(temp!=nullptr)
                return temp;
        }

    }
    //右孩子节点存不存在
    if(this->pRChild != nullptr)
    {
        //存在就看index和搜索的nodeIndex是不是相同
        if(this->pRChild->index == nodeIndex)
            return this->pRChild;
        else
        {
            temp = this->pRChild->searchNode(nodeIndex);
            return temp;
        }

    }
    return nullptr;
}
//删除节点，左右孩子指向空
void Node::DeleteNode() {
    //递归删除左孩子
    if(this->pLChild != nullptr)
        this->pLChild->DeleteNode();
    //递归删除右孩子
    if(this->pRChild != nullptr)
        this->pRChild->DeleteNode();
    //判断当前节点的父节点是否为空
    if(this->pParent!=nullptr)
    {
        //判断当前节点是左节点
        if(this->pParent->pLChild== this)
            this->pParent->pLChild = nullptr;
        //判断当前节点是右节点
        if(this->pParent->pRChild==this)
            this->pParent->pRChild = nullptr;
        //删除当前节点
    }
    delete this;
}
void Node::PerorderTraversal()
{
    std::cout<<this->index<<" "<<this->data<<" "<<"\n";
    if(this->pLChild!=nullptr)
        this->pLChild->PerorderTraversal();
    if(this->pRChild!=nullptr)
        this->pRChild->PerorderTraversal();
}
void Node::InorderTraversal() {
    if(this->pLChild!=nullptr)
        this->pLChild->InorderTraversal();
    std::cout<<this->index<<" "<<this->data<<" "<<"\n";
    if(this->pRChild!=nullptr)
        this->pRChild->InorderTraversal();
}
void Node::PosorderTraversal() {
    if(this->pLChild != nullptr)
        this->pLChild->PosorderTraversal();
    if(this->pRChild!=nullptr)
        this->pRChild->PosorderTraversal();
    std::cout<<this->index<<" "<<this->data<<" "<<"\n";
}